package com.tesisutn.restsoft.persistencia.implementaciones.base;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.tesisutn.restsoft.dominio.interfaces.ObjetoDeDominio;
import com.tesisutn.restsoft.persistencia.interfaces.base.Persistencia;

@Transactional
public class PersistenciaJPA<T extends ObjetoDeDominio> implements Persistencia<T> {
	@PersistenceContext
	protected EntityManager entityManager;
	
	private Class<T> type;
	
	public PersistenciaJPA(Class<T> type){
		super();
		this.type = type;
	}
	
	@Override
	@Transactional(readOnly=true)
	public T get(Object id) {
		if (id == null) {
			return null;
		} else {
			return entityManager.find(type, id);
		}
	}
	
	@Override
	public void remove(T entity) {
		entityManager.remove(entity);
	}

	@Override
	public void save(T entity) {
		entityManager.persist(entity);
	}
	
	@Override
	public void save(Iterable<T> entities) {
		for(T entity : entities)
			save(entity);
	}
	
	@Override
	public void update(T entity) {
		entityManager.merge(entity);
	}
	
	@Override
	public void update(Iterable<T> entities) {
		for(T entity : entities)
			update(entity);
	}

	@Override
	@Transactional(readOnly=true)
	public List<T> findAll() {
		return entityManager.createQuery("select o from " + type.getName() + " o").getResultList();
	}

}
